from application import app, db
from flask import Blueprint, request, make_response, redirect
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.libs.DataHelper import getCurrentTime
from common.models.mail_address import MailAddress
from common.models.mail_order import MailOrder
import json, requests

mail_page = Blueprint("mail_page", __name__)


@mail_page.route('/getaddresslist', methods=['GET', 'POST'])
def getaddresslist():
    req = request.values
    openid = req['openid'] if "openid" in req else ""
    a = MailAddress.query.filter_by(openid=openid, mark=1).all()
    rts = []
    for item in a:
        address = str(item.address)
        address = address.split('-')
        temp = dict(id=item.id, name=item.name, address=address, detail=item.detail, phone=item.phone)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_asci
    return json.dumps(rts, ensure_ascii=False)  # rts


@mail_page.route("/changeaddressmark", methods=["GET", "POST"])
def changeaddressmark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = MailAddress.query.filter_by(id=id).first()
    a.mark = mark
    db.session.commit()
    return ops_renderJSON(msg="该条记录已删除")


@mail_page.route('/postaddress', methods=['GET', 'POST'])
def postaddress():
    req = request.values
    name = req['name'] if "name" in req else ""
    phone = req['phone'] if "phone" in req else ""
    address = req['address'] if "address" in req else ""
    detail = req['detail'] if "detail" in req else ""
    openid = req['openid'] if "openid" in req else ""

    if len(name) < 1:
        return ops_renderErrJSON(msg="请输入姓名")

    if len(phone) < 6:
        return ops_renderErrJSON(msg="请输入手机")

    if len(address) < 1 or address == "请选择-请选择-请选择":
        return ops_renderErrJSON(msg="请选择地址")

    if len(detail) < 1:
        return ops_renderErrJSON(msg="请输入详细地址")

    Address = MailAddress()
    Address.name = name
    Address.phone = phone
    Address.address = address
    Address.detail = detail
    Address.openid = openid
    Address.mark = 1

    db.session.add(Address)
    db.session.commit()

    return json.dumps({"code": 200, "msg": "添加成功", }, indent=4,
                      sort_keys=True, default=str,
                      ensure_ascii=False)


@mail_page.route('/postmailorder', methods=['GET', 'POST'])
def postmailorder():
    req = request.values
    name = req['name'] if "name" in req else ""
    phone = req['phone'] if "phone" in req else ""
    address = req['address'] if "address" in req else ""
    detail = req['detail'] if "detail" in req else ""
    uid = req['uid'] if "uid" in req else ""
    city = req['city'] if "city" in req else ""
    sn = req['sn'] if "sn" in req else ""

    if len(name) < 1:
        return ops_renderErrJSON(msg="请输入姓名")

    if len(phone) < 6:
        return ops_renderErrJSON(msg="请输入手机")

    if len(address) < 1 or address == "请选择-请选择-请选择":
        return ops_renderErrJSON(msg="请选择地址")

    if len(detail) < 1:
        return ops_renderErrJSON(msg="请输入详细地址")

    else:
        Order = MailOrder()
        Order.name = name
        Order.phone = phone
        Order.address = address
        Order.detail = detail
        Order.uid = uid
        Order.mark = 1
        Order.sn = sn
        Order.city = city
        Order.created_time = Order.updated_time = getCurrentTime()

        db.session.add(Order)
        db.session.commit()

        return json.dumps({"code": 200, "msg": "申请成功", }, indent=4,
                          sort_keys=True, default=str,
                          ensure_ascii=False)


# 管理员获得申请列表
@mail_page.route("/showmailorder", methods=["GET", "POST"])
def showmailorder():
    req = request.values
    city = req['city'] if "city" in req else ""
    stime = req['stime'] if "stime" in req else ""
    etime = req['etime'] if "etime" in req else ""

    if len(stime) < 1:
        return ops_renderErrJSON(msg="请输入开始时间")
    if len(etime) < 1:
        return ops_renderErrJSON(msg="请输入结束时间")
    else:
        a = MailOrder.query.filter(MailOrder.mark != 0, MailOrder.city == city, MailOrder.created_time <= etime,
                                   MailOrder.created_time >= stime).all()
        rts = []
        for item in a:
            temp = dict(name=item.name, phone=item.phone, address=item.address, detail=item.detail,
                        creatername=item.creater.nickname, createrdep=item.creater.department, id=item.id)
            rts.append(temp)
        # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
        return json.dumps(rts, ensure_ascii=False)  # rts


@mail_page.route("/changemailmark", methods=["GET", "POST"])
def changemailmark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = MailOrder.query.filter_by(id=id).first()
    a.mark = mark
    db.session.commit()
    return ops_renderJSON(msg="状态变更成功")
